package com.shujia.flink.sql

import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.table.api.EnvironmentSettings
import org.apache.flink.table.api.bridge.scala.StreamTableEnvironment
import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala._
import org.apache.flink.types.Row

object Demo4ReadMysql {
  def main(args: Array[String]): Unit = {

    //flink  流处理的环境
    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //设置flink  sql 配置
    val bsSettings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner() // 使用blink 的计划器（解析sql）
      .inStreamingMode()
      .build()

    //创建table 环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)


    /**
      * jdbc: 如果作为source  --> 有界流
      * flink 表的结构必须和mysql中的表结构一致
      *
      */

    bsTableEnv.executeSql(
      """
        |
        |CREATE TABLE mysql_student (
        |  id STRING,
        |  name STRING,
        |  age INT,
        |  gender  STRING,
        |  clazz STRING,
        |  PRIMARY KEY (id) NOT ENFORCED
        |) WITH (
        |   'connector' = 'jdbc',
        |   'url' = 'jdbc:mysql://master:3306/student',
        |   'table-name' = 'student',
        |   'username'='root',
        |   'password'='123456'
        |)
        |
      """.stripMargin)


    bsTableEnv.executeSql(
      """
        |CREATE TABLE print_table(
        |clazz STRING,
        |c BIGINT
        |)
        |
        | WITH ('connector' = 'print')
        |
        """.stripMargin)


    bsTableEnv.executeSql(
      """
        |insert into print_table
        |select clazz,count(1) c  from mysql_student group by clazz
        |
      """.stripMargin)


  }

}
